<template>
    <div class="achievement-list-page">
        <el-card shadow="never" class="mt-4">
            <el-form inline @keyup.enter.native="onSubmit">
                <!-- <el-form-item label="企业">
                    <el-select
                        v-model="form.companyId"
                        clearable
                        @change="onSubmit">
                        <el-option
                            v-for="item in companyOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item label="关键词" prop="keyword">
                    <el-input
                    v-model="form.keyword"
                    placeholder="搜索用户名字和邮箱"
                    class="input-width"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input
                    v-model="form.phone"
                    placeholder="搜索用户手机号"
                    class="input-width"></el-input>
                </el-form-item>
                <el-button type="primary" @click="onSubmit">搜索</el-button>
                <el-button type="primary" @click="resetForm">重置</el-button>
            </el-form>
            <div class="mt-3" v-loading="loading">
                <el-table :data="data">
                    <el-table-column type="index"
                    :index="indexMethod"
                    align="center"
                    label="序号"
                    width="50"/>
                    <el-table-column label="姓名" prop="name" width="70"></el-table-column>
                    <el-table-column label="手机号" prop="phone"></el-table-column>
                    <el-table-column label="邮箱" prop="email"></el-table-column>
                    <el-table-column label="职位" prop="position"></el-table-column>
                    <el-table-column label="团队" prop="team"></el-table-column>
                    <el-table-column label="已使用天数">
                        <template slot-scope="{row}">
                            {{ row.active_time | usedDay(row.expiry_time, dateTimestamp, row.active_day) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="剩余天数">
                        <template slot-scope="{row}">
                            {{ restDayFilter(row.expiry_time) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="企业" prop="company" />
                    <el-table-column label="注册时间">
                        <template slot-scope="{row}">
                            {{ formatTime(row.created_at, 'YYYY-MM-DD') }}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="操作">
                        <template slot-scope="{row}">
                            <el-button type="text" @click="onViewClick(row)">学习统计</el-button>
                            <el-button type="text" @click="getUserData(row)">编辑</el-button>
                            <el-button type="text" @click="onRenewal(row)">续费</el-button>
                            <el-button
                                type="text"
                                class="red-color"
                                @click="onRestClick(row)">重置密码</el-button>
                            <el-button
                                type="text"
                                :class="row.status === 1 ? 'red-color' : ''"
                                @click="onStatusClick(row)">{{ row.status === 1 ? '冻结' : '恢复' }}</el-button>
                            <el-button type="text" @click="getUserDetail(row)">查看邀请</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="totalElements > 0" class="footer flex justify-end items-center">
                <pagination
                    ref="pagination"
                    :currentPage="form.page"
                    :pageSize="form.size"
                    :handleCurrentChange="onPageChange"
                    :handlePageSizeChange="onPageChange"
                    :totalElements="totalElements"
                ></pagination>
            </div>
        </el-card>

        <el-dialog
            title="用户邀请详情列表"
            :visible.sync="visible"
            width="60%"
            :modal-append-to-body="false"
        >
            <el-table :data="dialogData">
                <el-table-column align="center" label="账号" prop="email"/>
                <el-table-column align="center" label="员工头像">
                    <template slot-scope="{row}">
                        <img class="w-16 h-16" v-if="row.avatar" :src="row.avatar" alt="">
                    </template>
                </el-table-column>
                <el-table-column align="center" label="员工姓名" prop="name"/>
                <el-table-column align="center" label="手机号" prop="phone"/>
                <el-table-column align="center" label="邀请时间">
                    <template slot-scope="{row}">
                        {{ formatTime(row.created_at, 'YYYY-MM-DD') }}
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-center" v-if="dialogForm.total > 0">
                <el-pagination
                    @current-change="fetchInviteData"
                    :current-page.sync="dialogForm.page"
                    :page-size="dialogForm.size"
                    layout="total, prev, pager, next, jumper"
                    :total="dialogForm.total">
                </el-pagination>
            </div>
        </el-dialog>

        <el-dialog
            title="续费"
            :visible.sync="visibles"
            width="60%"
            :modal-append-to-body="false">
            <el-form
                label-width="130px"
                @submit.native.prevent>
                <el-form-item label="当前剩余天数:">{{ residueDays }}</el-form-item>
                <el-form-item label="操作:" required>
                    <el-radio-group v-model="renewalForm.is_plus_expired">
                        <el-radio :label="true">新增</el-radio>
                        <el-radio :label="false">扣减</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="天数:" required>
                    <el-input-number
                    v-model="renewalForm.expired_length"
                    :min="1"/></el-form-item>
            </el-form>
            <div class="flex justify-center">
                <el-button type="primary" @click="onRenewalSubmit">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="用户信息修改"
            :visible.sync="userVisible"
            width="60%"
            :modal-append-to-body="false">
            <el-form
                label-width="90px"
                label-position="right"
                @submit.native.prevent>
                <el-form-item label="姓名:">
                    <el-input class="input-width" v-model.trim="userForm.name" placeholder="请输入用户姓名"></el-input>
                </el-form-item>
                <el-form-item label="电话号码:">
                    <el-input class="input-width" v-model.trim="userForm.phone" placeholder="请输入电话号码"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="text-center">
                <el-button type="primary" @click="onChangeUser">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Pagination from '@/components/base/Pagination';
import TimeFormats from '@/helpers/TimeFormats';
import IndexNumber from '@/helpers/IndexNumber';

export default {
    components: {
        Pagination,
    },
    mixins: [require('@/mixins/CacheQuery').default],
    data() {
        return {
            loading: false,
            visible: false,
            visibles: false,
            userVisible: false,
            data: [],
            form: {
                page: 1,
                size: 50,
                companyId: '',
                keyword: '',
                isRegister: true,
                phone: '',
            },
            accountInfo: '',
            totalElements: 0,
            companyOptions: [],
            // 当前日期零时零分时间戳
            dateTimestamp: '',
            // 明日日期零时零分时间戳
            dialogData: [],
            // 当天时间戳
            tomorrowDateTimestamp: '',
            dialogForm: {
                size: 10,
                page: 1,
                total: 0,
            },
            dayTime: 0,
            // 剩余天数
            residueDays: 0,
            renewalForm: {
                is_plus_expired: true,
                expired_length: 1,
            },
            inviteId: 0,
            userForm: {
                name: '',
                phone: '',
            },
        };
    },
    filters: {
        usedDay(activeTime, expiryTime, dateTimestamp, activeDay) {
            if (activeTime && expiryTime) {
                if (dateTimestamp >= expiryTime) {
                    // 已过期
                    return activeDay;
                }
                // 未过期下 总天数 = 累积已使用天数 + 与当天计算已使用天数
                return activeDay + ((dateTimestamp - activeTime) / 86400);
            }
            return '';
        },
    },
    watch: {
        // dayTime(val) {
        //     this.renewalForm.is_plus_expired = this.residueDays < val;
        //     if (!val) {
        //         this.renewalForm.expired_length = this.residueDays;
        //     } else this.renewalForm.expired_length = Math.abs(this.residueDays - val);
        // },
        visibles(val) {
            if (!val) {
                this.residueDays = 0;
                this.renewalForm = {
                    is_plus_expired: true,
                    expired_length: 1,
                };
            }
        },
        userVisible(val) {
            if (!val) {
                this.userForm = {
                    name: '',
                    phone: '',
                };
            }
        },
    },
    methods: {
        initDateTimestamp() {
            const now = new Date();
            const date = new Date(now.toLocaleDateString());
            this.dateTimestamp = date.getTime() / 1000;
            this.tomorrowDateTimestamp = this.dateTimestamp + 86400;
        },
        formatTime(timestamp, format) {
            return timestamp ? new TimeFormats().convertTime(format, timestamp) : '';
        },
        onSubmit() {
            this.form.page = 1;
            this.fetchData();
        },
        onResetFilters() {
            this.$refs.form.resetFields();
        },
        onPageChange(val, text) {
            if (text) {
                this.form.size = val;
                this.form.page = 1;
            } else {
                this.form.page = val;
            }
            this.fetchData();
        },
        onDialog() {
            this.visible = !this.visible;
        },
        onRenewal(row) {
            this.loading = true;
            API.get(`user/${row.id}`).then(res => {
                this.visibles = !this.visibles;
                this.renewalForm = {...this.renewalForm, ...res};
                this.dayTime = this.restDayFilter(res.expiry_time);
                this.residueDays = this.restDayFilter(res.expiry_time);
            }).finally(() => this.loading = false);
        },
        onRenewalSubmit() {
            // if (!this.renewalForm.expired_length) {
            //     this.visibles = !this.visibles;
            //     return $ele.$message.warning('当前有效期不变');
            // }
            const id = this.renewalForm.id;
            this.loading = true;
            API.put(`user/register/${id}`, this.renewalForm).then(() => {
                $ele.$message.success('操作成功');
                this.fetchData();
                this.visibles = !this.visibles;
            }).finally(() => this.loading = false);
        },
        fetchData() {
            this.loading = true;
            API.get('user', {params: this.form}).then((res) => {
                this.data = res.content;
                this.totalElements = res.pagination.total;
            }).finally(() => this.loading = false);
        },
        onRestClick({id}) {
            this.confirmBox('是否重置该用户密码', `user/reset/${id}`, '操作成功', 'put', res => {
                $ele.$confirm(`重置密码成功，当前账号的登陆密码是${res.password}`, '提示', {
                    confirmButtonText: '确定',
                    type: 'warning',
                });
            });
        },
        onStatusClick(row) {
            const content = row.status === 1 ? '是否冻结此员工账号' : '是否解除此员工账号冻结状态';
            const requestStatus = row.status === 1 ? 2 : 1;
            this.confirmBox(content, `user/${row.id}/${requestStatus}`, '操作成功', 'put');
        },
        confirmBox(tip, url, message, api, fn) {
            $ele.$confirm(tip, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.loading = true;
                API[api](url).then(res => {
                    $ele.$message.success(message);
                    this.fetchData();
                    if (fn) fn(res);
                }).finally(() => this.loading = false);
            }).catch(() => { });
        },
        resetForm() {
            this.form.keyword = '';
            this.form.phone = '';
            this.form.companyId = '';
            this.onSubmit();
        },
        fetchCompany() {
            API.get('company/list').then((res) => {
                this.companyOptions = res;
            });
        },
        getUserDetail(row) {
            this.loading = true;
            this.inviteId = row.id;
            this.dialogForm.page = 1;
            API.get(`user/invite/${row.id}`, {params: this.dialogForm})
                .then((res) => {
                    this.dialogData = res.content;
                    this.dialogForm.total = res.pagination.total;
                    this.onDialog();
                }).finally(() => this.loading = false);
        },
        fetchInviteData() {
            this.loading = true;
            API.get(`user/invite/${this.inviteId }`, {params: this.dialogForm})
                .then((res) => {
                    this.dialogData = res.content;
                    this.dialogForm.total = res.pagination.total;
                }).finally(() => this.loading = false);
        },
        indexMethod(index) {
            return new IndexNumber()
                .getIndex(this.totalElements, this.form.page, this.form.size, index);
        },
        // 剩余天数
        restDayFilter(expiryTime) {
            if (expiryTime) {
                if (this.tomorrowDateTimestamp < expiryTime) {
                    return (expiryTime - this.tomorrowDateTimestamp) / 86400;
                }
            }
            return 0;
        },

        onUserDialog() {
            this.userVisible = !this.userVisible;
        },
        getUserData({id}) {
            this.loading = true;
            API.get(`user/${id}`).then(res => {
                this.userForm = res;
                this.onUserDialog();
            }).finally(() => this.loading = false);
        },
        onChangeUser() {
            const form = this.userForm;

            this.loading = true;
            API.put(`user/${form.id}`, form).then(() => {
                $ele.$message.success('修改成功');
                this.fetchData();
                this.onUserDialog();
            }).finally(() => this.loading = false);
        },

        onViewClick(row) {
            this.$router.push({
                name: 'Staff.Home',
                params: {
                    id: row.id || '',
                },
            });
        },
    },
    mounted() {
        this.initDateTimestamp();
        this.fetchData();
        this.fetchCompany();
    },
};
</script>

<style lang="scss">
.achievement-list-page {
    .filter {
        .input-width {
            max-width: 200px;
        }
    }

    .input-width {
        max-width: 300px;
    }

    .footer {
        height: 44px;
        background: #f7f7f7;
        padding-left: 20px;
        padding-right: 20px;
    }
}
</style>
